import { createStore , combineReducers } from 'redux' ;

import { INCREASE , DECREASE  } from '../actions/counter';

const counterInitState = { 
    value: 0 
}

const counterReducer = ( state = counterInitState , action )=>{
    switch( action.type ) {
        case INCREASE :
            return { value: state.value + 1 }
        case DECREASE :
            return { value: state.value - 1 }
        default:
            return state ;
    }
}

const cartInitState = {
    items: [
        { id: 123 , name: '红米 10A' , price: 649 , number: 10 } ,
        { id: 456 , name: '魅蓝 10' , price: 699 , number: 8 } ,
        { id: 789 , name: '红米 Note 11 Pro' , price: 1699 , number: 5 } 
    ]
}

const cartReducer = ( state = cartInitState , action )=>{
    let arr = [ ...state.items ] ;
    let id = action.id ;
    let item = arr.find( e => e.id === id );
    switch( action.type ) {
        case '增加' :
            console.log( '增加' );
            item.number++;
            return { items: arr } ;
        case '减少' :
            console.log( '减少' );
            item.number--;
            return { items: arr } ;
        default:
            return state ;
    }
}

// 将多个 Reducer 合并
const reducer = combineReducers( { 
    counter: counterReducer , 
    cart: cartReducer 
} );

const store = createStore( reducer );

export default store ;